//趋势分析 查询趋势分析数据
srvMap.add('queryTrendChartsList','','front/sh/sceneMonitor!execute?uid=queryTrendChartsList');
//下载--趋势分析
srvMap.add('dlTrendChartsList','','front/sh/export!execute?uid=dlTrendChartsList');


var myChart_trendCharts; // 趋势分析图
var allRegionList=null;//全量景区列表
var lastQueryParamObj={};	//最近一次查询param--用于查询和下载同条件

$(function() {

	initPage();
	initSearch();
	//初始化日期组件
	initDate();

	//绑定日期类型radio切换事件
	$('input[name=dataTimeType]').on("change",function(){
		if( $(this).val() == "day" ){
			$("#dateTimeStart").show();
			$("#dateTimeEnd").show();
			$("#dateTimeOnly").hide();			
		}
		if( $(this).val() == "hour" ){
			$("#dateTimeStart").hide();
			$("#dateTimeEnd").hide();
			$("#dateTimeOnly").show();			
		}
		if( $(this).val() == "month" ){
			$("#dateTimeStart").hide();
			$("#dateTimeEnd").hide();
			$("#dateTimeOnly").hide();
		}
	});
	
	//绑定查询事件
	$(".select_button").click(function(){
		var data = getParams("query");
		
		if ("hour" == data.cycleId) {
			if( data.startTime == null || data.startTime.length == 0 ){
				alert("请选择数据查询日期！");
				return false;
			}
		} else if ("day" == data.cycleId) {
			if( data.startTime == null || data.startTime.length == 0 ){
				alert("请选择查询开始时间！");
				return false;
			}
			
			if( data.endTime == null || data.endTime.length == 0 ){
				alert("请选择查询结束时间！");
				return false;
			}
			
			//限制时间跨度
			if( DateDiff($('#dateStart').val(),$('#dateEnd').val()) > 30 ){
				alert("开始结束日期的跨度大于一个月，请重新选择！");
				return false;
			}
		}
		
		showTrendCharts(data);
	});
	
	//绑定下载导出
	$("#exportData").on("click",function(){
		downloadData();
	});
});

/**
 * 初始化页面
 * @return {[type]} [description]
 */
function initPage() {
	//initCityList();
	//initRegionTypeList();
	//initRegionList();
	
	Util.loadUpInfo.initCityList();
	Util.loadUpInfo.initRegionTypleList();
	Util.loadUpInfo.initRegionList();
	
	//展示折线图
	var data = getParams("query");
	//接收景区子监控页面传来的参数
	if( in_regionId != null && in_regionId.length > 0 ){
		data.regionId = in_regionId;
		$("#divselectInput").val(in_regionName);
		$("#inputselect").val(in_regionId);
		
		//$("#divselectInput").val(decodeURIComponent(regionName));
		//$('#inputselect').val(lastQueryParamObj.regionId);		
	}
	showTrendCharts(data);
}

/**
 * 选择地市，修改景区列表初始化
 */
function changeCityId() {
	initRegionList(); //重新初始化景区列表
}

/**
 * 选择景区类型，修改景区列表初始化
 */
function changeRegionType() {
	initRegionList(); //重新初始化景区列表
}

/**
 * 显示趋势分析图
 */
function showTrendCharts(paramObj) {
	var par = "&cityId="+paramObj.cityId+"&regionType="+paramObj.regionType+"&cycleId="+paramObj.cycleId+
				"&startTime="+paramObj.startTime+"&endTime="+paramObj.endTime+"&regionId="+paramObj.regionId;
	Util.ajax.postJsonSync(srvMap.get('queryTrendChartsList'), par, function(json,status){
		if(status){
			finishQueryTrendChart(json.object.data,paramObj.startTime);
		}else{
			 alert('错误','数据异常！');   
		}
	});
//	var url = CONTENT_PATH + "/com.asiainfo.zhly.AnalysisAction.queryTrendChartsList.invoke";
//	Base.ajax({
//		url: url,
//		data: paramObj,
//		success: function(req) {
//			// 展示趋势图表 
//			finishQueryTrendChart(req);
//		}
//	});
}

function finishQueryTrendChart(req,startDate) {
	hideLoading(myChart_trendCharts);
	if (null == req || null == req.chartList || req.chartList.length == 0) {
		 noDataShowSource(myChart_trendCharts, 'trendChartsDiv');
		 
		 //无数据时，禁用下载按钮
		 $("#exportData").attr("disabled","disabled");
		 return;
	}

	$("#exportData").removeAttr("disabled");
	
	var chartList = req.chartList;
	var lineData = [];
	var xData = [];
	var isTimeData = false;
	var xName = "";
	
	for (var i = 0; i < chartList.length; i++) {
		var proValue = chartList[i].countValue;
		var proName = chartList[i].countName;
		if( proName.length == 10 ){	//时刻表
			proName = proName.slice(8);
			isTimeData = true;
		}

		lineData.push(Number(proValue));
		xData.push(proName);
	}
	
	if( isTimeData ){
		xData=['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'];
		var date = new Date();
		var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + month + strDate;
        if(currentdate==startDate){
		var h=new Date().getHours();
		for(var i in xData){
			  if(parseInt(xData[i]) ==h){
				  var num=parseInt(i)+1;
			    lineData=lineData.slice(0,num);   
			  }
			}
        }
	}
	
	var _axisLabel = {};
	
	if( proName.length == 2 ){
		xName='小时';
	}else if( proName.length == 6 ){
		xName='月';
	}else{
		xName='日';
		//日期展示时，X轴倾斜
		_axisLabel = {
			margin : 5,
			rotate : 45,
			textStyle : {
				align : 'left'
			}
		};
	}
	
	require.config({
		paths: {
			echarts: CONTENT_PATH + '/common/js'
		}
	});
	require(['echarts', 'echarts/chart/line'], function(ec) {
		var averageVal = calculateAverage(lineData);
		option = {
			title: {
				text: ''
			},
			tooltip: {
				trigger: 'item',
				formatter: "{b}:<br/> {a}：{c}"
			},
			calculable: false,
			/*grid: {
				borderWidth: 0,
				x: 90,
				y: 60,
				x2: 90,
				y2: 40,
				borderColor: '#424242'
			},*/
			xAxis: [{
				name:xName,
				type: 'category',
				boundaryGap: false,
				axisLabel:_axisLabel,
				data: xData
			}],
			yAxis: [{
				name: "人数",
				type: 'value',
				show: true
			}],
			series: [{
				name: '客流人数',
				type: 'line',
				markPoint: {
					//symbol:'emptyRectangle',
					data: [{
						type: 'max',
						name: '最大值'
					}, {
						type: 'min',
						name: '最小值'
					}]
				},
				markLine: {
					data : [
				        [
				            {name: '平均值', value: averageVal, xAxis: xData[0], yAxis: averageVal},
				            {name: '', xAxis:xData[xData.length-1] , yAxis: averageVal}
				        ]
				    ]},
				data: lineData
			}]
		};

		myChart_trendCharts = ec.init(document.getElementById('trendChartsDiv'), 'macarons');
		myChart_trendCharts.clear();
		myChart_trendCharts.setOption(option);
	});
}

/*
 * 计算趋势分析的平均值
 * @author:xw.jiang
 * @date:2016/1/13
 */
function calculateAverage(lineData){
	var sum=0;
	for(var i=0;i<lineData.length;i++){
		sum+=lineData[i]
	} 
	return parseInt(sum/lineData.length);
}

function hideLoading(chart) {
	if (chart != null) {
		chart.hideLoading();
	}
}

function noDataShowSource(chart, id) {
	if (chart == null) {
		require.config({
			paths: {
				echarts: CONTENT_PATH + '/common/js'
			}
		});
		require(['echarts', 'echarts/chart/map', 'echarts/chart/line', 'echarts/chart/bar', 'echarts/chart/pie'], function(ec) {
			chart = ec.init(document.getElementById(id), 'macarons');
			chart.clear();
			showEmptyTip(chart);
		});
	} else {
		showEmptyTip(chart);
	}
}

function showEmptyTip(chart) {
	chart.clear();
	if (chart != null) {
		chart.showLoading({
			text: '当前未查询到数据，请稍后再试',
			effect: 'bubble',
			textStyle: {
				fontSize: 22
			}
		});
	}
}

/**
 * 下载趋势分析统计数据
 * 
 * @author menxl
 * xiangzp
 */
function downloadData() {
	var paramObj = getParams("query");
	//接收景区子监控页面传来的参数
	if( in_regionId != null && in_regionId.length > 0 ){
		
		$("#divselectInput").val(in_regionName);
		$("#inputselect").val(in_regionId);
	}
	var params  = "&cityId="+paramObj.cityId+"&regionType="+paramObj.regionType+"&cycleId="+paramObj.cycleId+
	"&startTime="+paramObj.startTime+"&endTime="+paramObj.endTime+"&regionId="+paramObj.regionId;
	var url = srvMap.get('dlTrendChartsList');
	_postSubmit(url, params.split("&"));
	return;
//	Util.ajax.postJsonSync(srvMap.get('dlTrendChartsList'), par, function(json,status) {
//		if(status){
//			alert("下载文件");
//		}else{
//			alert('错误','数据异常！');
//		}
//	});
//	var str = getParams("download");
//	window.open(CONTENT_PATH + "/com.asiainfo.zhly.AnalysisAction.downloadTrendChartsList.invoke?" + str, '_blank');
}

/**
 * 初始化地市列表
 */
function initCityList() {
	var par = "";
	Util.ajax.postJsonSync(srvMap.get('queryCityList'),par,function(json,status){
		if(status){
			finishQueryCityList(json.object.cityData);
		}else{
			alert('错误','数据异常！');
		}
	});
	//初始化地市列表
//	var url = CONTENT_PATH + "/com.asiainfo.zhly.AnalysisAction.queryCityList.invoke";
//	Base.ajax({
//		url: url,
//		success: function(req) {
//			var cityList = req.cityList;
//			finishQueryCityList(cityList);
//		}
//	});
}

/**
 * 初始化地市列表
 * @param cityList
 */
function finishQueryCityList(cityList) {
	var cityHtml = '';

	for (var i = 0; i < cityList.length; i++) {
		cityHtml += '<option value="' + cityList[i].city_id + '">' + cityList[i].city_name + '</option>';
	}
	$('#cityId').html(cityHtml);
}

/**
 * 初始化景区类型列表
 */
function initRegionTypeList() {
	var par = "";
	Util.ajax.postJsonSync(srvMap.get('queryRegionTypleList'),par,function(json,status){
		if(status){
			finishQueryRegionTypeList(json.object.regionTypeData);
		}else{
			alert('错误','数据异常！');
		}
	});
	//初始化景区类型列表
//	var url = CONTENT_PATH + "/com.asiainfo.zhly.AnalysisAction.queryRegionTypeList.invoke";
//	Base.ajax({
//		url: url,
//		success: function(req) {
//			var regionTypeList = req.regionTypeList;
//			finishQueryRegionTypeList(regionTypeList);
//		}
//	});
}

/**
 * 初始化景区类型列表
 * @param regionTypeList
 */
function finishQueryRegionTypeList(regionTypeList) {
	var regionTypeHtml = '';
	for (var i = 0; i < regionTypeList.length; i++) {
		regionTypeHtml += '<option value="' + regionTypeList[i].region_type + '">' + regionTypeList[i].region_type_name + '</option>';
	}
	$('#regionTypeId').html(regionTypeHtml);
}

/**
 * 获取参数
 * @param paramType： query-查询参数json类型；download-下载参数string类型
 * @returns {___anonymous8779_8904}
 */
function getParams(paramType) {
	var cityId = $('#citySelect span li').attr("d_value")|| "";
	var regionId = $('#inputselect').val()|| "";
	var cycleId = $('input[name="dataTimeType"]:checked').val();
	var regionType = "";	
	regionType = $('#regionTypleSelect span li').attr("d_value")|| "";
	
	if ("query" == paramType) {
		var paramData = {
			cityId: cityId,
			regionType: regionType,
			regionId: regionId,
			cycleId: cycleId
		};

		if ("hour" == cycleId) {
			paramData.startTime = $('#dateTime').val().replace("-","").replace("-","");
		} else if ("day" == cycleId) {
			paramData.startTime = $('#dateStart').val().replace("-","").replace("-","");
			paramData.endTime = $('#dateEnd').val().replace("-","").replace("-","");
		}

		return paramData;
	} else {
		//编码加密
		cityId = encodeURIComponent(cityId).EncodeBase64();
		regionType = encodeURIComponent(regionType).EncodeBase64();
		regionId = encodeURIComponent(regionId).EncodeBase64();

		var startTime = "";
		var endTime = "";
		
		if ("hour" == cycleId) {
			startTime = $('#dateTime').val().replace("-","").replace("-","");;
			endTime = $('#dateTime').val().replace("-","").replace("-","");;
		} else if ("day" == cycleId) {
			startTime = $('#dateStart').val().replace("-","").replace("-","");;
			endTime = $('#dateEnd').val().replace("-","").replace("-","");;
		}

		cycleId = encodeURIComponent(cycleId).EncodeBase64();
		startTime = encodeURIComponent(startTime).EncodeBase64();
		endTime = encodeURIComponent(endTime).EncodeBase64();
		
		var str = 'cityId=' + cityId + '&regionType=' + regionType + '&regionId=' + regionId + '&cycleId=' + cycleId;
		str += "&startTime=" + startTime;
		str += "&endTime=" + endTime;
		return str;
	}
}

/**
 * 初始化景区列表
 */
function initRegionList() {
	$('#regionId').html();
	$("#divselectInput").val("搜索景区，请输入名称");
	var cityId = $('#cityId').val();
	var regionType = $('#regionTypeId').val();
	if (cityId==null||typeof(cityId) == 'undefined') {
		cityId="";
	}
	if (regionType==null||typeof(regionType) == 'undefined') {
		regionType="";
	}
	var par = "&cityId="+cityId+"&regionType="+regionType;
	Util.ajax.postJsonSync(srvMap.get("queryRegionList"), par, function(json,status){
		if(status){
			finishQueryRegionList(json.object.regionData);
			allRegionList = json.object.regionData;
		}else{
			 alert('错误','数据异常！');
		}
	})
	//初始化景区列表
//	var url = CONTENT_PATH + "/com.asiainfo.zhly.AnalysisAction.queryRegionList.invoke";
//	var data = {
//		"cityId": cityId,
//		"regionType": regionType
//	}
//	Base.ajax({
//		url: url,
//		data: data,
//		success: function(req) {
//			var regionList = req.regionList;
//			allRegionList=regionList;
//			finishQueryRegionList(regionList);
//		}
//	});
}

function finishQueryRegionList(regionList) {
	var regionHtml = '';
	for (var i = 0; i < regionList.length; i++) {
		regionHtml += '<option value="' + regionList[i].region_id + '">' + regionList[i].region_name + '</option>';
	}
	$('#regionId').html(regionHtml);
	$.divselect("#divselect","#inputselect",regionList);
}

/**
 * 初始化日期组件
 */
function initDate() {

	var startTime = {
		elem: '#dateTime',
		format: 'YYYY-MM-DD',
		min: laydate.now(-30),
		max: laydate.now(), //最大日期
		istime: false,
		istoday: true
	};
	var startDate = {
		elem: '#dateStart',
		format: 'YYYY-MM-DD',
		min: laydate.now(-183), //设定最小日期为当前日期
		max: laydate.now(-1), //最大日期
		istime: false,
		istoday: true,
		choose: function(datas) {
			endDate.min = datas; //开始日选好后，重置结束日的最小日期
			endDate.start = datas; //将结束日的初始值设定为开始日
		}
	};
	var endDate = {
		elem: '#dateEnd',
		format: 'YYYY-MM-DD',
		min: laydate.now(-30),
		max: laydate.now(-1),
		istime: false,
		istoday: true,
		choose: function(datas) {
			/*dateStr = getOtherDate(datas, 30);
			if (dateStr < dayMinDate) {
				startDate.min = dayMinDate;
			} else {
				startDate.min = dateStr;
			}*/
			startDate.max = datas; //结束日选好后，重置开始日的最大日期
		}
	};
	laydate(startTime);
	laydate(startDate);
	laydate(endDate);
	$("#dateTime").val(laydate.now());
	$("#dateEnd").val(laydate.now(-1));
	$("#dateStart").val(laydate.now(-30));
}


/**
 * @Description : 计算日期相差天数
 * 
 * @return void
 *
 * @author : xuxiong
 * @date : 2015年12月24日 下午5:40:08 
 *
 */
function  DateDiff(sDate1,sDate2){    //sDate1和sDate2是2006-12-18格式  
    var aDate,oDate1,oDate2,iDays;
    aDate  =  sDate1.split("-");
    oDate1 =  new  Date(aDate[0]  +  '-'  +  aDate[1]  +  '-'  +  aDate[2]);
    aDate  =  sDate2.split("-");  
    oDate2 =  new  Date(aDate[0]  +  '-'  +  aDate[1]  +  '-'  +  aDate[2]);
    iDays  =  parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24);	//把相差的毫秒数转换为天数  
    return  iDays;
}

/**
 * 初始化景区搜索绑定事件
 * @Description : 
 * 
 * @return void
 *
 * @author : pengjy
 * @date : 2015年12月13日 下午5:40:08 
 *
 */
function initSearch(){
	$("#divselectInput").keyup(function(){
		var searchValue = $("#divselectInput").val();
		var resultRegionList=[];
		if (searchValue==null||searchValue==""||typeof(searchValue)=="undefined") {
			resultRegionList=allRegionList;
		}else {
			for (var i = 0; i < allRegionList.length; i++) {
				if (allRegionList[i].region_name.indexOf(searchValue)>-1) {
					resultRegionList.push(allRegionList[i]);
				}
			}
		}
		$.divselect("#divselect","#inputselect",resultRegionList);
	});
}


/**
 * 用POST提交解决参数过长
 */
var _postSubmit = function(url, params) {
	var exportForm = document.createElement("FORM");
	document.body.appendChild(exportForm);
	exportForm.method = "POST";

	if (null != params && params.length > 0)
		for ( var i = 0; i < params.length; i++) {
			var param = params[i].split("=");
			var inputElement = document.createElement("input");
			inputElement.setAttribute("name", param[0]);
			inputElement.setAttribute("type", "hidden");
			exportForm.appendChild(inputElement);
			inputElement.value = fromatParam(param);
		}

	exportForm.action = url;
	exportForm.submit();

	document.body.removeChild(exportForm);
};
var fromatParam = function(param) {
	var res = "";
	for (var i = 1; i < param.length; i++) {
		res += param[i];
		if (i < (param.length - 1)) {
			res += "=";
		}
	}
	return res;
};